package com.hongtech.modules.common;

import com.hongtech.common.bean.Token;
import com.hongtech.common.enums.Action;
import com.hongtech.common.util.IpUtils;
import com.hongtech.common.util.TokenUtil;
import com.hongtech.framework.anno.Login;
import com.hongtech.modules.system.entity.SysUserEntity;
import com.hongtech.modules.system.service.SysLogService;
import com.hongtech.modules.system.service.SysUserService;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.base.Captcha;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.IOException;

/**
 * 登录控制器
 */
@Controller
@RequestMapping("/login")
public class LoginController extends BaseController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysLogService sysLogService;

    /**
     * 登录页面
     */
    @Login(action = Action.Skip)
    @RequestMapping("")
    public String login() {
        return "login";
    }

    /**
     * 执行登录
     */
    @Login(action = Action.Skip)
    @RequestMapping(value = "/doLogin", method = RequestMethod.POST)
    public String doLogin(HttpServletRequest request, String userName, String password,
            String captcha, Model model) {
        if (StringUtils.isBlank(userName) || StringUtils.isBlank(captcha)
                || StringUtils.isBlank(captcha)) {
            model.addAttribute("error", "用户名/密码/验证码不能为空.");
            return "login";
        }
        String sessionCaptcha = (String) request.getSession().getAttribute("captcha");
        if (StringUtils.isBlank(sessionCaptcha)) {
            model.addAttribute("error", "验证码已过期,请重新输入.");
            return "login";
        }
        if (!captcha.equals(sessionCaptcha)) {
            model.addAttribute("error", "验证码错误.");
            return "login";
        }
        SysUserEntity sysUserEntity = sysUserService.login(userName, password);
        if (sysUserEntity == null) {
            model.addAttribute("error", "用户名或密码错误.");
            return "login";
        }
        // 登录成功
        String loginUserName = sysUserEntity.getUserName();
        Token token = new Token();
        token.setUid(sysUserEntity.getId());
        token.setUname(loginUserName);
        token.setIp(IpUtils.getIpAddr(request));
        TokenUtil.addToken(token, request);
        // 记录登录日志
        String title = "用户登录成功";
        sysLogService.insertLog(title, loginUserName, request.getRequestURI(), "******");
        return redirectTo("/index");
    }

    /**
     * 验证码获取
     */
    @Login(action = Action.Skip)
    @RequestMapping("/captcha")
    public void captcha(HttpServletRequest req, HttpServletResponse res) throws IOException {
        res.setContentType("image/gif");
        res.setHeader("Pragma", "No-cache");
        res.setHeader("Cache-Control", "no-cache");
        res.setDateHeader("Expires", 0);
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(125, 33);
        captcha.setCharType(Captcha.TYPE_DEFAULT);
        captcha.out(res.getOutputStream());
        req.getSession().setAttribute("captcha", captcha.text());
    }

    /**
     * 退出系统
     *
     * @return 登陆页面
     */
    @Login(action = Action.Skip)
    @RequestMapping(value = "/logout")
    public String logout(HttpServletRequest req) throws IOException {
        Token st = TokenUtil.getToken(req);
        TokenUtil.clearLogin(req);
        String title = "用户退出系统";
        String uname = st != null ? st.getUname() : "***";
        sysLogService.insertLog(title, uname, req.getRequestURI(),"******");
        return redirectTo("/index");
    }

}
